package com.polaris.live.viewmodel

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.NetworkUtils
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.common.resp.VersionResp
import com.polaris.live.common.util.DateUtils
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.manager.DownFileManager
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.net.liveService
import com.polaris.live.net.payerService
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.LiveResourceConfigResp
import com.polaris.live.resp.back_resp.PartyGamingResp
import com.polaris.live.resp.back_resp.UserConsumableRewardV2Resp
import com.polaris.live.resp.go_resp.QuickLoginBean
import com.polaris.live.resp.go_resp.UserIdRequest
import com.polaris.live.ui.live.activity.LiveSpectatorActivity
import com.polaris.live.ui.live.activity.StartMatchActivity
import com.polaris.live.utils.TaskRedProxy
import com.polaris.live.utils.file.FileUtils.getPagFile
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 * MainViewModel
 *
 * @author Created by 半仙 on 2023/10/18/018 10:35
 */
class MainViewModel : BaseViewModel() {

    val mUpdateLiveData = MutableLiveData<VersionResp>()

    fun getUser() {
        request({ userService.getUserData() }, {
            UserManager.setUser(it)
        })
    }

    fun quickLogin() {
        request({ userService.quickLogin(QuickLoginBean()) }, {
            UserManager.setUser(it)
        })
    }

    fun updateVersion() {
        request({ userService.updateVersion() }, {
            mUpdateLiveData.value = it
        })
    }

    fun getGifts() {
        request({ payerService.getGiftList() }, {
            CommonCache.setGiftResp(it)
        })
    }

    //获取下载的pag
    fun downloadPag() {
        if (NetworkUtils.isWifiConnected()) {
            request({ userService.getAnimation() }, {
                viewModelScope.launch(CoroutineScopeManager.ioDispatcher) {
                    val deferredList = it.map { item ->
                        async {
                            try {
                                DownFileManager.loadFile(getPagFile(), item)
                            } catch (e: Exception) {
                                LogExt.logI("--downLoad") {
                                    "${e.message}"
                                }
                            }
                        }
                    }
                    deferredList.awaitAll()
                }
            })
        }
    }

    //结束直播状态
    fun liveEndState() {
        request({ liveService.liveEndState() }, {})
    }

    //结束游戏作为状态
    fun partyGameSiteEnd() {
        request({ liveService.partyGameSiteEnd() }, {})
    }

    //获取游戏状态
    val mPartyGameLiveData = MutableLiveData<ResultState<PartyGamingResp>>()
    fun partyGameGaming() {
        request({ liveService.partyGameGaming() }, mPartyGameLiveData)
    }

    //结束游戏状态
    fun partyGameEnd() {
        request({ liveService.partyGameEnd() }, {})
    }

    //结束通话状态
    fun callEndState() {
        request({ liveService.callEndState() }, {})
    }

    //清除无用的截图和压缩后的图片
    fun clearPhotos(cacheDir: File) {
        viewModelScope.launch(CoroutineScopeManager.ioDispatcher) {
            try {
                val luBanDir = File(cacheDir, "luban")
                val imageFiles = cacheDir.listFiles { file ->
                    file.isFile && (file.name.endsWith(".jpg", true) || file.name.endsWith(
                        ".jpeg",
                        true
                    ))
                }

                imageFiles?.forEach { file ->
                    file.delete()
                }

                if (luBanDir.exists() && luBanDir.isDirectory) {
                    luBanDir.listFiles()?.forEach { file ->
                        file.delete()
                    }
                }
            } catch (_: Exception) {
            }
        }
    }

    val mLiveResourceLiveData = MutableLiveData<ResultState<LiveResourceConfigResp>>()
    fun getLiveResource() {
        request({ liveService.getLiveResource() }, mLiveResourceLiveData)
    }

    private var mTimingJob: Job? = null

    //开始计时三分钟后继续弹出
    fun timingLivingDialog(context: Context) {
        val newLivingCount = CommonCache.getNewLivingCount()
        if (newLivingCount >= MAX_SHOW_DIALG) return
        mTimingJob = viewModelScope.launch {
            delay(MILLISECONDS)
            if (LiveStateManager.getState() != LiveConst.State.NONE) {
                checkStateShow(ViewUtils.getAliveTopActivity() ?: context)
            } else {
                withContext(CoroutineScopeManager.mainDispatcher) {
                    val finalContext = ViewUtils.getAliveTopActivity() ?: context
                    if (finalContext is StartMatchActivity || finalContext is LiveSpectatorActivity) {
                        timingLivingDialog(finalContext)
                    } else {
                        GlobalDialogManager.showNewLiving(finalContext)
                    }
                }
            }
        }
    }

    private var mCheckJob: Job? = null
    private fun checkStateShow(context: Context) {
        mCheckJob = viewModelScope.launch {
            while (isActive && LiveStateManager.getState() != LiveConst.State.NONE) {
                delay(CHECK_STATE)
            }
            //留1秒时间给通话结束页做缓冲  不然有可能导致dialog在还没有进入结束页的时候弹出
            delay(1000)
            withContext(CoroutineScopeManager.mainDispatcher) {
                val finalContext = ViewUtils.getAliveTopActivity() ?: context
                if (finalContext is StartMatchActivity || finalContext is LiveSpectatorActivity) {
                    timingLivingDialog(finalContext)
                } else {
                    GlobalDialogManager.showNewLiving(finalContext)
                }
            }
        }
    }

    //领取道具每日奖励  聚合
    val mConsumableReceiveLiveData = MutableLiveData<ResultState<List<UserConsumableRewardV2Resp>>>()
    fun consumableReceive() {
        val time = CommonCache.getPolymerizationTime() ?: 0
        val nowTime = System.currentTimeMillis()
        if (!DateUtils.isOneDay(time, nowTime)) { //不是一天才请求
            request({ userService.consumableReceive(UserIdRequest(UserManager.getUserId())) },
                {
                    mConsumableReceiveLiveData.value = ResultState.onAppSuccess(it)
                    CommonCache.savePolymerizationTime(nowTime)
                }
            )

        }
    }

    override fun onCleared() {
        super.onCleared()
        mTimingJob?.cancel()
        mTimingJob = null

        mCheckJob?.cancel()
        mCheckJob = null
    }

    /**
     * 定时请求任务红点
     */
    private var mTaskJob: Job? = null
    fun checkTaskRedShow() {
        mTaskJob = viewModelScope.launch {
            while (isActive) {
                request({ userService.getTaskNew() }, {
                    TaskRedProxy.update(it)
                })
                delay(TASK_RED)
            }

        }
    }

    companion object {

        //3分钟   弹出开播引导弹窗
        const val MILLISECONDS = 180000L

        //每天弹出3次
        const val MAX_SHOW_DIALG = 3

        //如果是在直播或者通话就先不弹  每个5秒检出一次状态
        const val CHECK_STATE = 5000L

        const val TASK_RED = 30000L

    }
}